<?php

function fertilizer_case_list_page()
{
    @$output = drupal_render(drupal_get_form('fertilizer_case_list_form'));
    return $output;
}

function fertilizer_case_overview_page(){
    @$output = drupal_render(drupal_get_form('fertilizer_case_overview_form'));
    return $output;
}
function fertilizer_case_list_form($form, &$form_state)
{
    if (!empty($_GET['addr_id'])) {
        $form_state['addr_id'] = $_GET['addr_id'];
    }
    if(!empty($form_state['addr_id'])){
        $form['#addr_id'] = $form_state['addr_id'];
    }
    if (!empty($_GET['farmer_id'])) {
        $form_state['farmer'] = $_GET['farmer_id'];
    }
    if(!empty($form_state['farmer'])){
        $form['#farmer'] = $form_state['farmer'];
    }

    if(empty($form_state['farmer'])&& empty($form['#addr_id'])){
        $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state);
        $form['address'] = _insert_address_selection_form($form, $form_state, 'address', 5, FALSE, _get_address_id($form_state), '', '');
    }
    $form['plant'] = _insert_plant_selection_form($form,$form_state,!empty($record) ? $record->plant_id:'');
    if(!empty($_GET['special_activities'])){
        $special_activities_title = get_special_activities_title($_GET['special_activities']);
    }
    $form['special_activities'] = array(
        '#type' => 'textfield',
        '#title' => '专项活动',
        '#size' => 32,
        '#maxlength' => 50,
        '#id'=>'special_activities_textfield',
        '#default_value' => $special_activities_title,
    );
    $table['#markup'] = data_list_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');

    return $form;
}

function fertilizer_case_list_form_validate($form, &$form_state)
{
}

function data_list_view_page($form = '', &$form_state = '')
{
    global $user;
    $user_info = _get_user_info($user->uid);
    //表头
    $header = array(
        array('data' => '选择', 'class' => ['essential no']),
        isset($form_state['addr_id']) && !empty($form_state['addr_id'])?"":
        array('data' => '地址', 'class' => ['essential province city county']),
        isset($form_state['farmer']) && !empty($form_state['farmer'])?"":
            array('data' => '农户', 'class' => ['essential more']),
        array('data' => '农作物', 'class' => ['essential more']),
        array('data' => '效果描述', 'class' => ['essential more']),
        array('data' => '实际产量', 'class' => ['essential more']),
        array('data' => '操作', 'class' => ['essential more']),
    );
    $output = '';
    $query = db_select('fertilizer_case', 'C')->extend('PagerDefault')->extend('TableSort');
    $query->join('farmer', 'F', 'C.farmer_id=F.farmer_id');
    $query->join('plant', 'P', 'C.plant_id=P.plant_id');
    $query->join('addr', 'A', 'A.addr_id=F.addr_id');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.addr_id');
    $query->leftJoin('addr', 'A5', 'A.village_id=A5.addr_id');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('A5', 'name', 'village');

    //地址级别查询
    _address_search_conditon($query,$form_state);

    $query->fields('C');
    $query->addField('F', 'farmer_name');
    $query->addField('P', 'plant_name');
    if(empty($form_state['values']) || empty($form_state['values']['order'])) {
        $query->orderBy('C.timestamp', 'DESC');
    }

    if (!empty($form_state['values']['plant'])) {//
        $query->condition('C.plant_id', get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false), '=');
    }
    //专项活动
    if(!empty($form_state['values']['special_activities'])){
        $special_activities_id = get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities'],false);
        if(!empty($special_activities_id)){
            $query->condition('C.special_activities_id',$special_activities_id, '=');
        }else{
            $query->condition('C.special_activities_id',0, '=');
        }
    }
    if(!empty($_GET['special_activities'])){
        $query->condition('C.special_activities_id',$_GET['special_activities'], '=');
    }
    if(!empty($_GET['farmer_id'])){
        $query->condition('C.farmer_id',$_GET['farmer_id']);
        $form_state['farmer'] = $_GET['farmer_id'];
    }
    if (!empty($form_state['farmer'])) {//
        $query->condition('C.farmer_id', $form_state['farmer'], '=');
    }
    if (!empty($form_state['addr_id'])) {//
        $query->condition('F.addr_id', $form_state['addr_id'], '=');
    }
    if (!empty($form_state['values']['farmer_id'])) {//
        $query->condition('C.farmer_id', $form_state['values']['farmer_id'], '=');
    }
    if ($user_info['role'] != '农户') {
        if (!user_access('view all fertilizer_case') && user_access('view own fertilizer_case')) {
            $query->condition('C.author_uid', $user->uid, '=');
        }
    }
    $query->limit(variable_get("list_page_item_number", 5));
    $fertilizer_caseInfo = $query->orderByHeader($header)->execute();
    $rows = array();
    //表内容
    $n = 1;
    foreach ($fertilizer_caseInfo as $row) {
        $city = $row->city ? ' ' . $row->city : '';
        $county = $row->county ? ' ' . $row->county : '';
        $town = $row->town ? ' ' . $row->town : '';
        $village = $row->village ? ' ' . $row->village : '';

        if (nonghua_user_access('fertilizer_case', 'delete', $row->fertilizer_case_id, $row->author_uid, $row->farmer_id)) {
            $disabled = ' class="listViewTableCheck" ';
        } else{
            $disabled = ' disabled="true" ';
        }

        $rows[] = array(
            array('data' => "<input type='checkbox'".$disabled." value ='" . $row->fertilizer_case_id . "' name='" . $row->fertilizer_case_id . "'/>" . $n++, 'class' => 'integrant essential no'),
            isset($form_state['addr_id']) && !empty($form_state['addr_id'])?"":
            array('data' => $row->province . $city . $county.$town.$village, 'class' => ['integrant essential province city county'],"style" => ['width: 150px']),
            isset($form_state['farmer']) && !empty($form_state['farmer'])?"":
                array('data' => '<a href="' . base_path() . 'farmer/edit/' . $row->farmer_id . '?farmer_id='.$row->farmer_id.'">' . $row->farmer_name . '</a>', 'class' => ['integrant essential store-name'],"style" => ['width: 50px']),
            array('data' => $row->plant_name, 'class' => ['integrant goRight essential phone'],"style" => ['width: 50px']),
            array('data' => $row->effect_desc, 'class' => ['integrant goRight essential phone']),
            array('data' => $row->real_yield, 'class' => ['integrant goRight essential phone'],"style" => ['width: 50px']),
            (isset($form_state['farmer']) && !empty($form_state['farmer']))||(isset($form_state['addr_id']) && !empty($form_state['addr_id']))?
                array('data' => '<a href="' . base_path() . 'fertilizer_case/edit/' . $row->fertilizer_case_id .'?'.
                    (isset($form_state['addr_id']) && !empty($form_state['addr_id'])?'addr_id='.$form_state['addr_id'].'&':'').
                    (isset($form_state['farmer']) && !empty($form_state['farmer'])?'farmer_id='.$form_state['farmer']:'').
                    '" target="_self"><img width="15px" height="15px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>','class' => 'essential more' ,"style" => ['width: 70px']):
                array('data' => '<a href="' . base_path() . 'fertilizer_case/edit/' . $row->fertilizer_case_id . '" data-toggle="modal" target="_self"><img width="20px" height="20px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more' ,"style" => ['width: 70px']),
        );
    }

    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced')))); //表格
    /*	 * *按钮** */
    if (sizeof($rows) > 0 && (user_access('delete own fertilizer_case') ||  user_access('delete all fertilizer_case'))) {
        $output .= '<a href="javascript:void(0)" id="listViewTableSelectAll" data-toggle="modal" class="btn btn-mini">全选</a>';
        $output .= '<a href="javascript:void(0)" id="listViewTableDeleteSelected" data-toggle="modal" class="btn btn-mini">删除所选</a>';
    }
    if(!empty($form_state['values']['village'])){
        $addr_id = $form_state['values']['village'];
        $str = 'village=';
    }elseif(!empty($form_state['values']['town'])){
        $addr_id = $form_state['values']['town'];
        $str = 'town=';
    }elseif(!empty($form_state['values']['county'])){
        $addr_id = $form_state['values']['county'];
        $str = 'county=';
    }elseif(!empty($form_state['values']['city'])){
        $addr_id = $form_state['values']['city'];
        $str = 'city=';
    }elseif(!empty($form_state['values']['province'])){
        $addr_id = $form_state['values']['province'];
        $str = 'province=';
    }
    $str .= $addr_id;
    $output .= '<a href="'.base_path().'fertilizer_case/export?'.$str.'&plant='.$form_state['values']['plant'].'&special_activities='.$form_state['values']['special_activities'].'" data-toggle="modal" class="btn btn-mini">导出</a>';
    $output .= theme('pager');
    return $output;
}

function fertilizer_case_overview_form($form, &$form_state)
{
    if (!empty($_GET['addr_id'])) {
        $form_state['addr_id'] = $_GET['addr_id'];
    }
    if(!empty($form_state['addr_id'])){
        $form['#addr_id'] = $form_state['addr_id'];
    }
    if (!empty($_GET['farmer_id'])) {
        $form_state['farmer'] = $_GET['farmer_id'];
    }
    if(!empty($form_state['farmer'])){
        $form['#farmer'] = $form_state['farmer'];
    }

//    if(empty($form_state['farmer'])&& empty($form['#addr_id'])){
//        $form['address'] = _insert_address_selection_form($form, $form_state, 'address', 5, FALSE, _get_address_id($form_state), '', '');
//    }
//    $form['plant'] = _insert_plant_selection_form($form,$form_state,!empty($record) ? $record->plant_id:'');
    $form['#fertilizer'] = data_overview_view_page($form, $form_state);
//    ajax_submit_form($form, $form_state, $table, '');

    return $form;
}


function data_overview_view_page($form = '', &$form_state = ''){
    global $user;
    $user_info = _get_user_info($user->uid);
    $query = db_select('fertilizer_case', 'C');
    $query->join('farmer', 'F', 'C.farmer_id=F.farmer_id');
    $query->join('plant', 'P', 'C.plant_id=P.plant_id');
    $query->join('addr', 'A', 'A.addr_id=F.addr_id');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.addr_id');
    $query->leftJoin('addr', 'A5', 'A.village_id=A5.addr_id');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('A5', 'name', 'village');
    //地址级别查询
    if (!empty($form_state['values']['village'])) {//村落级
        $query->condition('A.village_id', $form_state['values']['village'], '=');
    } else if (!empty($form_state['values']['town'])) {//乡镇级
        $query->condition('A.town_id', $form_state['values']['town'], '=');
    } elseif (!empty($form_state['values']['county'])) {//县级
        $query->condition('A.county_id', $form_state['values']['county'], '=');
    } elseif (!empty($form_state['values']['city'])) {//市级
        $query->condition('A.city_id', $form_state['values']['city'], '=');
    } elseif (!empty($form_state['values']['province'])) {//省级
        $query->condition('A.province_id', $form_state['values']['province'], '=');
    }
    $query->fields('C');
    $query->addField('F', 'farmer_name');
    $query->addField('P', 'plant_name');
    if(empty($form_state['values']) || empty($form_state['values']['order'])) {
        $query->orderBy('C.timestamp', 'DESC');
    }

    if (!empty($form_state['values']['plant'])) {//
        $query->condition('C.plant_id', $form_state['values']['plant'], '=');
    }
    if(!empty($_GET['farmer_id'])){
        $query->condition('C.farmer_id',$_GET['farmer_id']);
        $form_state['farmer'] = $_GET['farmer_id'];
    }
    if (!empty($form_state['farmer'])) {//
        $query->condition('C.farmer_id', $form_state['farmer'], '=');
    }
    if (!empty($form_state['addr_id'])) {//
        $query->condition('F.addr_id', $form_state['addr_id'], '=');
    }
    if (!empty($form_state['values']['farmer_id'])) {//
        $query->condition('C.farmer_id', $form_state['values']['farmer_id'], '=');
    }
    $query->range(0,20);
    if ($user_info['role'] != '农户') {
        if (!user_access('view all fertilizer_case') && user_access('view own fertilizer_case')) {
            $query->condition('C.author_uid', $user->uid, '=');
        }
    }
    $fertilizer_caseInfo = $query->execute()->fetchAll();
    return $fertilizer_caseInfo;
}

function fertilizer_case_delete()
{
    ajax_table_delete('fertilizer_case', 'fertilizer_case_id');
//    ajax_table_delete('fertilizer_case_extra', 'fertilizer_case_id');
}


function fertilizer_case_export($form,&$form_state){
    $letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
    $tableheader = array('地址','农户','农作物','效果描述','实际产量');
    $data = get_fertilizer_case_data($form, $form_state);
    nonghua_php_excel($letter,$tableheader,$data,'施肥案例数据');
}

function get_fertilizer_case_data($form = '', &$form_state = ''){
    global $user;
    $user_info = _get_user_info($user->uid);
    $query = db_select('fertilizer_case', 'C');
    $query->join('farmer', 'F', 'C.farmer_id=F.farmer_id');
    $query->join('plant', 'P', 'C.plant_id=P.plant_id');
    $query->join('addr', 'A', 'A.addr_id=F.addr_id');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.addr_id');
    $query->leftJoin('addr', 'A5', 'A.village_id=A5.addr_id');
    
    //地址级别查询
    if (!empty($_GET['village'])) {//村落级
        $query->condition('A.village_id', $_GET['village'], '=');
    } else if (!empty($_GET['town'])) {//乡镇级
        $query->condition('A.town_id', $_GET['town'], '=');
    } elseif (!empty($_GET['county'])) {//县级
        $query->condition('A.county_id', $_GET['county'], '=');
    } elseif (!empty($_GET['city'])) {//市级
        $query->condition('A.city_id', $_GET['city'], '=');
    } elseif (!empty($_GET['province'])) {//省级
        $query->condition('A.province_id', $_GET['province'], '=');
    }
    
    if(empty($form_state['values']) || empty($_GET['order'])) {
        $query->orderBy('C.timestamp', 'DESC');
    }

    if (!empty($_GET['plant'])) {//
        $query->condition('C.plant_id', $_GET['plant'], '=');
    }
    //专项活动
    if(!empty($_GET['special_activities'])){
        $special_activities_id = get_id_from_string_field('special_activities','special_activities_id','title',$_GET['special_activities'],false);
        if(!empty($special_activities_id)){
            $query->condition('C.special_activities_id',$special_activities_id, '=');
        }else{
            $query->condition('C.special_activities_id',0, '=');
        }
    }

    if(!empty($_GET['farmer_id'])){
        $query->condition('C.farmer_id',$_GET['farmer_id']);
        $form_state['farmer'] = $_GET['farmer_id'];
    }
    if (!empty($form_state['farmer'])) {//
        $query->condition('C.farmer_id', $form_state['farmer'], '=');
    }
    if (!empty($form_state['addr_id'])) {//
        $query->condition('F.addr_id', $form_state['addr_id'], '=');
    }
    if (!empty($_GET['farmer_id'])) {//
        $query->condition('C.farmer_id', $_GET['farmer_id'], '=');
    }
    if ($user_info['role'] != '农户') {
        if (!user_access('view all fertilizer_case') && user_access('view own fertilizer_case')) {
            $query->condition('C.author_uid', $user->uid, '=');
        }
    }
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('A5', 'name', 'village');
    $query->addField('F', 'farmer_name');
    $query->addField('P', 'plant_name');
    $query->fields('C',array('effect_desc','real_yield'));
    
    $fertilizer_caseInfo = $query->execute()->fetchAll();
    foreach($fertilizer_caseInfo as $k => $v){
        $fertilizer_caseInfo[$k]->province= $v->province.$v->city.$v->county.$v->town.$v->village;
        unset($fertilizer_caseInfo[$k]->city);
        unset($fertilizer_caseInfo[$k]->county);
        unset($fertilizer_caseInfo[$k]->town);
        unset($fertilizer_caseInfo[$k]->village);
    }
    return $fertilizer_caseInfo;
}


